package com.pro.common.log.warn.service.unit;

import com.pro.baoyi.api.logWarn.enums.EnumSuccessFlag;
import com.pro.baoyi.api.logWarn.model.db.LogFileSizeRecord;
import com.pro.baoyi.api.logWarn.model.db.LogFileSizeWarningConfig;
import com.pro.baoyi.api.logWarn.model.db.LogFileSizeWarningConfigMultiple;
import com.pro.common.api.model.BaseModel;
import com.pro.common.log.warn.service.LogFileSizeRecordService;
import com.pro.common.log.warn.service.LogFileSizeWarningConfigMultipleService;
import com.pro.common.log.warn.service.LogFileSizeWarningConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class LogFileSizeUnitService {
    @Autowired
    private LogFileSizeRecordService logFileSizeRecordService;
    @Autowired
    private LogFileSizeWarningConfigService logFileSizeWarningConfigService;
    @Autowired
    private LogFileSizeWarningConfigMultipleService logFileSizeWarningConfigMultipleService;

    @Transactional(rollbackFor = Exception.class)
    public void handLogFileSizeRecord(){
        List<LogFileSizeWarningConfig> allConfig = getAllConfig();
        List<String> moduleNames = allConfig.stream().map(LogFileSizeWarningConfig::getModule).toList();
        List<LogFileSizeWarningConfig> updateConfigs = new ArrayList<>();
        Map<String, List<LogFileSizeRecord>> moduleRecordMap = logFileSizeRecordService.getThirdMap(moduleNames);
        allConfig.forEach(config -> {
            List<LogFileSizeRecord> records = moduleRecordMap.get(config.getModule());
            if (records == null || records.isEmpty()) {
                return;
            }
            // 遍历该模块的所有记录
            records.forEach(record -> {
                processRecord(config, config.getLogFileSizeWarningConfigMultiples(), record,updateConfigs);
            });
        } );
        logFileSizeWarningConfigService.updateBatchById(updateConfigs);

    }
    public void processRecord(LogFileSizeWarningConfig config, List<LogFileSizeWarningConfigMultiple> multiples, LogFileSizeRecord record, List<LogFileSizeWarningConfig> updateConfigs) {

        BigDecimal increaseSize = record.getIncreaseSize();

        LocalDateTime recordCreateTime = record.getCreateTime();
        LocalTime todayStartTime = recordCreateTime.toLocalTime();

        BigDecimal multiplier = new BigDecimal(1);
        for (LogFileSizeWarningConfigMultiple multiple : multiples) {
            if (isInTimeRange(todayStartTime, multiple.getStartTime(), multiple.getEndTime())) {
                multiplier = multiple.getMultiple();
                break;
            }
        }

        BigDecimal allowedFileSize = config.getNormalFileSizeInTime().multiply( multiplier);

        if (allowedFileSize.compareTo( increaseSize)<0) {
            LogFileSizeWarningConfig updateConfig = new LogFileSizeWarningConfig();
            updateConfig.setId(config.getId());
            updateConfig.setStatus(EnumSuccessFlag.FAIL);
            updateConfig.setStatusLast(EnumSuccessFlag.FAIL);
            updateConfig.setStatusLastFailTime(recordCreateTime);
            updateConfig.setStatusLastFailFileSize(record.getFileSize());
            updateConfig.setStatusLastFailFileIncreaseSize(increaseSize);
            updateConfigs.add(updateConfig);
        }else{
            LogFileSizeWarningConfig updateConfig = new LogFileSizeWarningConfig();
            updateConfig.setId(config.getId());
            updateConfig.setStatus(EnumSuccessFlag.SUCCESS);
            updateConfigs.add(updateConfig);
        }
    }


    private List<LogFileSizeWarningConfig> getAllConfig() {
        List<LogFileSizeWarningConfig> configs = logFileSizeWarningConfigService.list();
        List<Long> configIds = configs.stream().map(BaseModel::getId).toList();
        Map<Long, List<LogFileSizeWarningConfigMultiple>> multipleServiceListMap = logFileSizeWarningConfigMultipleService.getListMap(LogFileSizeWarningConfigMultiple::getConfigId, configIds);
        configs.forEach(config -> {
            config.setLogFileSizeWarningConfigMultiples(multipleServiceListMap.get(config.getId()));
        });
        return configs;
    }
    private boolean isInTimeRange(LocalTime recordCreateTime, LocalTime startTime, LocalTime endTime) {
        return !recordCreateTime.isBefore(startTime) && !recordCreateTime.isAfter(endTime);
    }


}
